//
//  ZoomsdkManger.swift
//  1meeting
//
//  Created by zhangheng on 2019/7/31.
//  Copyright © 2019 www.zhangheng.com. All rights reserved.
//

import Foundation
import ZoomSDK

enum ZoomUserType {
    case sdk
    case api
}


struct ZoomApiInfo {
    var type:ZoomUserType = .sdk
    var zak:String?
    var userID: String?
    var userToken: String?
    var displayName: String?
    var meetingNumber: String?
    var isDirectShare: Bool  = false
    var sharedApp: CGDirectDisplayID = 0
    var isVideoOff:Bool = false
    var isAuidoOff:Bool = false
    var vanityID:String? = nil
    var password:String?
    var ownid: String?
    var encryption:String?
}

class ZoomsdkManger: NSObject {
    static let shared = ZoomsdkManger()
    
    //zoom初始化
    public func sdkAuth(_ customizedFlag:Bool) -> () {
        self.initSDK(customizedFlag)
        self.authService!.delegate = self
        self.authService?.sdkAuth(kZoomSDKKey, appSecret: kZoomSDKSecret)
    }
    
    lazy var authService: ZoomSDKAuthService? = {
        let service = self.sdk?.getAuthService()
        return service
    }()
    
    func initSDK(_ customizedFlag:Bool) {
        ZoomsdkManger.setLang()
        ZoomSDK.shared().initSDK(customizedFlag)
    }
    
    lazy var sdk: ZoomSDK? = {
        let sdk = ZoomSDK.shared()
        sdk?.zoomDomain = kZoomSDKDomain
        sdk?.setAppLocale(ZoomSDKLocale_CN)
        return sdk
    }()
    
    
    
    class func setLang() -> () {
        //设置语言
        //您应该在应用程序中调用[[ ZoomSDK sharedSDK] initSDK：NO / YES] 之前先调用该方法，否则，应在重置首选语言后重新启动应用程序。
        let dlang = (ZoomSDK.shared()?.getLanguageArray()[1] as? String) ?? "zh-Hans"
        let lang = UserInfoManager.shared.lang ?? dlang
        ZoomSDK.shared()?.setPreferLanguage(lang)
        
    }
 
    public func rtcSetting() -> () {
        //self.setLang()
        
        let meeting = ZoomSDK.shared().getMeetingService()
        meeting?.delegate = self
        
        //let streamhelp = meeting?.getLiveStreamHelper()
        //streamhelp?.startLiveStream(byURL: "", streamKey: "", broadcastURL: "")
        
        //设置
        let settings = ZoomSDK.shared().getSettingService()
        let videoSet = settings?.getVideoSetting()
        //videoSet?.displayUserName(onVideo: false)
        videoSet?.enableBeautyFace(true)
        //videoSet?.enableCatchHDVideo(true)
        //videoSet?.enableMirrorEffect(true)
        //videoSet?.disableVideoJoinMeeting(true)
        //videoSet?.onDisplayUpTo49(inWallView: true)
        
        //let generalSetting =  ZoomSDK.shared()?.getSettingService()?.getGeneralSetting()
        //let zoomError = generalSetting?.setCustomInviteURL("www.baidu.com")
        //let actionCtrl = ZoomSDK.shared()?.getMeetingService()?.getMeetingActionController()
        //ZoomSDK.shared()?.getMeetingService().in
        
        //print(zoomError)
        
        //let shared = ZoomSDK.shared().getMeetingService().getMeetingConfiguration()
        //let shareHelp = ZoomSDK.shared().getPremeetingService()
    }
    
    
    func setLive(_ turnOn:Bool) -> () {
        if turnOn == true {
            let ret = ZoomSDK.shared().getMeetingService().getLiveStreamHelper().startLiveStream(byURL: UserInfoManager.shared.LiveURL!, streamKey: UserInfoManager.shared.LiveToken, broadcastURL: UserInfoManager.shared.PlayUrl)
            print(ret)
        }else { ZoomSDK.shared().getMeetingService().getLiveStreamHelper().stopLiveStream()
        }
    }
    
    func getMeetingService() -> ZoomSDKMeetingService? {
        let service = ZoomSDK.shared().getMeetingService()
        
        let config = service?.getMeetingConfiguration()
        //config?.hideMainWindowMeetingInfo = true
        config?.hideCopyURLButtonWhenInviteOthers = true
        config?.hideCopyInvitationButtonWhenInviteOthers = true
        //config?.hideInviteInMeetingH323CallInTab = true
        //config?.hideInviteInMeetingH323CallOutTab = true
        config?.hideFullPhoneNumber4PureCallinUser = true
        //config?.hideTelephoneInAudiowWindow = true
        config?.disableRenameInMeeting = true
        config?.hideSDKButtons(true, buttonType: ToolBarInviteButton)
        //config?.disableCustomLiveStreamAction = true
        
        
        if let roomid =  UInt32(UserInfoManager.shared.roomId?.clearId() ?? "000000") {
            config?.modifyWindowTitle(true, newMeetingNum: roomid)
        }
        
        let asc = ZoomSDK.shared().getMeetingService().getASController()
        asc?.delegate = self
        if asc != nil {
           asc?.startAppShare(0)
        }
        return service
    }
    
    
    //主持会议
    public func doHostMeeting(info:ZoomApiInfo,delegatek:ZoomSDKMeetingServiceDelegate?) {
        let service = self.getMeetingService()
        if delegatek != nil {
            service?.delegate = delegatek
        }
        if service != nil {
            if info.type == .api {
                service?.startMeeting(ZoomSDKUserType_APIUser, userID: info.userID, userToken: info.userToken, displayName: info.displayName, meetingNumber: info.meetingNumber, isDirectShare: info.isDirectShare, sharedApp: info.sharedApp, isVideoOff: info.isVideoOff, isAuidoOff: info.isAuidoOff, vanityID: info.vanityID)
            }else {
                service?.startMeeting(withZAK: info.zak, userType: SDKUserType_APIUser, userID: info.userID, userToken: info.userToken, displayName: info.displayName, meetingNumber: info.meetingNumber, isDirectShare: info.isDirectShare, sharedApp: info.sharedApp, isVideoOff: info.isVideoOff, isAuidoOff: info.isAuidoOff, vanityID: info.vanityID)
            }
        }
    }
    
    //加入会议
    public func doJoinMeeting(info:ZoomApiInfo,delegatek:ZoomSDKMeetingServiceDelegate?) {
        let service = self.getMeetingService()
        if delegatek != nil {
            service?.delegate = delegatek
        }
        if service != nil {
            service?.joinMeeting(ZoomSDKUserType_APIUser, toke4enfrocelogin: nil, webinarToken: nil, participantId: nil, meetingNumber: info.meetingNumber, displayName: info.displayName, password: info.password, isDirectShare: info.isDirectShare, sharedApp: info.sharedApp, isVideoOff: info.isVideoOff, isAuidoOff: info.isAuidoOff, vanityID: info.vanityID)
        }
    }
    
    class func isMeetingHost() -> Bool{
        return false
    }
}

extension ZoomsdkManger:ZoomSDKMeetingServiceDelegate {
    //MARK:ZoomSDKMeetingServiceDelegate
    func onMeetingStatusChange(_ state: ZoomSDKMeetingStatus, meetingError error: ZoomSDKMeetingError, end reason: EndMeetingReason) {
        switch state {
        case ZoomSDKMeetingStatus_Idle:
            print("No meeting is running.")
        case ZoomSDKMeetingStatus_Connecting:
            //LoadViewController.show()
            print("ZoomSDKMeetingStatus_Connecting")
        case ZoomSDKMeetingStatus_WaitingForHost:
            print("ZoomSDKMeetingStatus_WaitingForHost")
        case ZoomSDKMeetingStatus_InMeeting:
            print("ZoomSDKMeetingStatus_InMeeting")
        case ZoomSDKMeetingStatus_Disconnecting:
            print("ZoomSDKMeetingStatus_Disconnecting")
        case ZoomSDKMeetingStatus_Reconnecting:
            print("ZoomSDKMeetingStatus_Reconnecting")
        case ZoomSDKMeetingStatus_Failed:
            print("ZoomSDKMeetingStatus_Failed")
        case ZoomSDKMeetingStatus_Ended:
            print("ZoomSDKMeetingStatus_Ended")
        case ZoomSDKMeetingStatus_AudioReady:
            print("ZoomSDKMeetingStatus_AudioReady")
        case ZoomSDKMeetingStatus_OtherMeetingInProgress:
            print("ZoomSDKMeetingStatus_OtherMeetingInProgress")
        case ZoomSDKMeetingStatus_InWaitingRoom:
            print("ZoomSDKMeetingStatus_InWaitingRoom")
        case ZoomSDKMeetingStatus_WaitExternalSessionKey:
            print("ZoomSDKMeetingStatus_WaitExternalSessionKey")
        case ZoomSDKMeetingStatus_Webinar_Promote:
            print("ZoomSDKMeetingStatus_Webinar_Promote")
        case ZoomSDKMeetingStatus_Webinar_Depromote:
            print("ZoomSDKMeetingStatus_Webinar_Depromote")
        default:
            break
        }
    }
}

extension ZoomsdkManger:ZoomSDKASControllerDelegate{
    func onZoomAuthIdentityExpired() {
        
    }
}

extension ZoomsdkManger: ZoomSDKAuthDelegate {
    func onZoomSDKAuthReturn(_ returnValue: ZoomSDKAuthError) {
        switch returnValue {
        case ZoomSDKAuthError_Success:
            print("初始化成功")
        default:
            print("初始化失败")
        }
    }
    
    
    func onSharing(_ status: ZoomSDKShareStatus, user userID: UInt32) {
        switch status {
        case ZoomSDKShareStatus_None:
            break
        default:
            break
        }
    }
    
}

extension ZoomsdkManger: ZoomSDKDirectShareHelperDelegate  {
    func onDirectShareStatusReceived(_ status: DirectShareStatus, directShareReceived handler: ZoomSDKDirectShareHandler!) {
        
    }
    
    
    
    
}



